import commonjs from '@rollup/plugin-commonjs';
import nodeResolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';
import rollupPluginInjectProcessEnv from 'rollup-plugin-inject-process-env';
import fs from 'fs';

const htmlTmp = async ({ files }) => {
  const jsFile = files.js.find(file => {
    const reg = /index.*?.js$/;
    return reg.test(file.fileName);
  });
  const res = await new Promise((resolve, reject) => {
    fs.readFile('public/template.html', { encoding: 'utf-8' }, (err, res) => {
      if (err) {
        return reject(err);
      }
      resolve(res);
    });
  });
  const finallyFilePath = res.replace(/{{.+}}/, jsFile.fileName);
  return finallyFilePath;
};

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/index.js',
    format: 'esm',
    sourcemap: true,
  },
  plugins: [
    livereload({ watch: ['dist', 'public'] }),
    serve({
      open: true,
      port: 8000,
      openPage: '/template.html',
      contentBase: ['public', 'dist'],
    }),
    commonjs(),
    rollupPluginInjectProcessEnv({
      NODE_ENV: 'production', //'development',
    }),
    nodeResolve(),
    babel({
      exclude: 'node_modules/**',
      babelHelpers: 'runtime',
    }),
  ],
};
